<template>
	<div>
		<el-upload :action="uploadUrl" :limit="99" :on-exceed="uploadOverrun" :on-success="handleGalleryUrl"
			:on-remove="handleRemove" :file-list="fileList" multiple accept=".jpg, .jpeg, .png, .gif" list-type="picture-card">
			<i class="el-icon-plus"/>
		</el-upload>
		<div class=" xc-text-right">
			<el-button type='primary' @click="confirm">确定</el-button>
		</div>
	</div>
	<!-- </dialogWrap> -->
</template>

<script>
	import {
		CODE,
		uploadUrl
	} from '@/common/apiconfig';
	export default {
		props: {
			value: null,
			valueKey: '',
		},
		data() {
			return {
				imgPath: [],
				uploadUrl, //: process.env.VUE_APP_BASE_API + "upload/uploadImg",
			}
		},
		computed: {
			fileList() {
				let that = this;
				try {
					if (this.valueKey) {
						return this.value.map(i => ({
							url: i[this.valueKey]
						}))
					} else {
						return this.value.map(i => ({
							url: i
						}))
					}
				} catch (error) {
					console.log(error);
					return [];
				}
			}
		},
		inject: ['vm'],
		mounted() {
			this.imgPath = this.value.map(i => {
				if (this.valueKey) return i[this.valueKey];
				return i;
			});
		},
		methods: {
			handleGalleryUrl(response, file, fileList) {
				if (response[CODE.code] === CODE.success) {
					this.imgPath.push(response.data);
				}
			},
			confirm() {
				let arr = this.imgPath;
				if (this.valueKey) {
					arr = arr.map(i => {
						var obj = {};
						obj[this.valueKey] = i;
						return obj;

					})
				}
				this.$emit('input', arr);
				this.cancel()
			},
			cancel() {
				this.vm.$refs.imgs.onCancel();
			},
			// 超过数量
			uploadOverrun: function() {
				this.$toast("上传文件个数超出限制!最多上传5张图片!");
			},
			handleRemove: function(file, fileList) {
				for (var i = 0; i < this.imgPath.length; i++) {
					// 这里存在两种情况
					// 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
					//    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
					// 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
					var url
					if (file.response === undefined) {
						url = file.url
					} else {
						url = file.response.data
					}
					if (this.imgPath[i] === url) {
						this.imgPath.splice(i, 1)
					}
				}

			},
		}
	}
</script>

<style>

</style>